package cn.petplatform.utils;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LNL
 * @date 2021/5/21 10:19
 */
public class ProcessFileUtils {

    //文件根路径
    private static final String ROOT_PATH = "/static/upload";
    //请求文件时的名称
    private static final String REQUEST_FILE_NAME = "picture";

    /**
     * 传入文件全路径(处理文件时返回的路径)
     * @param path
     */
    public static void failDeleteFile(String path) {
        try {
            String filePath = ResourceUtils.getURL("classpath:").getPath() + path;
            File file = new File(filePath);
            if (file.isFile()) {
                file.delete();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("服务器错误");
        }
    }

    /**
     * @param request 处理二进制的MultipartHttpServletRequest
     * @return 包含filePath文件全路径、fileName原始名称
     */
    //处理文件,如果处理成功，返回一个文件路径
    public static Map<String,String> processFile(MultipartHttpServletRequest request) {
        Map<String,String> data = new HashMap<>();
        MultipartFile picture = request.getFile(REQUEST_FILE_NAME);
        //文件的路径
        String filePath = "";
        try {
            String realPath = ResourceUtils.getURL("classpath:").getPath() + ROOT_PATH;
            File baseDir = new File(realPath);
            if (!baseDir.exists()) {
                baseDir.mkdirs();
            }
            //获取文件原始名字
            String originalFilename = picture.getOriginalFilename();
            //获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //创建新的文件名
            String newFileName = UUIDUtils.getUUID() + suffix;
            //上传文件
            picture.transferTo(new File(realPath,newFileName));
            //图片上传成功后，返回图片全路径
            filePath = ROOT_PATH+"/"+newFileName;
            data.put("filePath",filePath);
            data.put("fileName",originalFilename.substring(0,originalFilename.lastIndexOf(".")));
        } catch (Exception e) {
            //如果失败，将文件删除
            ProcessFileUtils.failDeleteFile(filePath);
            throw new RuntimeException("图片处理异常,请重新上传");
        }
        return data;
    }

}
